import React, { useEffect, useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Table, Pagination, Spin, message } from 'antd';
import axios from 'axios';
import './FundPage.scss'; // 可根据需要自定义样式

const FundPage = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

  const [data, setData] = useState([]);
  const [totalPages, setTotalPages] = useState(58); // 你可以根据后端实际页数调整
  const [loading, setLoading] = useState(false);

  const token = localStorage.getItem("jwt_token");

  useEffect(() => {
    if (!token) {
      message.error("用户未登录");
      navigate("/login");
    }
  }, [token, navigate]);

  useEffect(() => {
    if (!searchParams.get('page')) {
      setSearchParams({ page: '1' });
    }
  }, [searchParams, setSearchParams]);

  const page = parseInt(searchParams.get('page') || '1', 10);

  useEffect(() => {
    if (!token) return;

    const fetchFundData = async () => {
      setLoading(true);
      try {
        const res = await axios.get(`/api/ui/fund?page=${page}`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (res.data.code === 0) {
          setData(res.data.data);
        } else {
          message.error("获取数据失败：" + res.data.message);
        }
      } catch (err) {
        message.error("请求出错");
      } finally {
        setLoading(false);
      }
    };

    fetchFundData();
  }, [page, token]);

  const columns = [
    { title: '基金代码', dataIndex: '基金代码', key: 'code' },
    { title: '基金名称', dataIndex: '基金名称', key: 'name' },
    { title: '最新价', dataIndex: '最新价', key: 'price', render: val => (val / 1000).toFixed(3) },
    { title: '涨跌额', dataIndex: '涨跌额', key: 'delta', render: val => (val / 1000).toFixed(3) },
    { title: '涨跌幅', dataIndex: '涨跌幅', key: 'percent', render: val => (val / 100).toFixed(2) + '%' },
    { title: '成交量', dataIndex: '成交量', key: 'volume', render: val => (val / 10000).toFixed(2) + '万' },
    { title: '成交额', dataIndex: '成交额', key: 'amount', render: val => (val / 10000).toFixed(2) + '万' },
    { title: '开盘价', dataIndex: '开盘价', key: 'open', render: val => (val / 1000).toFixed(3) },
    { title: '最高价', dataIndex: '最高价', key: 'high', render: val => (val / 1000).toFixed(3) },
    { title: '最低价', dataIndex: '最低价', key: 'low', render: val => (val / 1000).toFixed(3) },
    { title: '昨收', dataIndex: '昨收', key: 'prevClose', render: val => (val / 1000).toFixed(3) },
  ];

  return (
    <div className="fund-page">
      <h2>基金行情</h2>
      <Spin spinning={loading}>
        <Table
          dataSource={data}
          columns={columns}
          rowKey={record => record['基金代码']}
          pagination={false}
          scroll={{ x: 'max-content' }} 
        />
        <Pagination
          current={page}
          pageSize={20}
          total={totalPages * 20}
          onChange={(newPage) => setSearchParams({ page: newPage.toString() })}
          showSizeChanger={false}
        />
      </Spin>
    </div>
  );
};

export default FundPage;
